URL={
	cart_add:'cart/add_cart',
	cart_remove:'cart/remove'
}
MALL = {
	init:function(){
		this.menu.init();
		this.cart.init();
	},
	menu:{
		details:{},
		init:function(){
			var self = this;
			//mall_info
			$(document).on('bc-info-success',"#mall-menu-info", function(event) {
				var e = $(this);
				$('#mall-menu-info .menu-info-add-to-cart').addClass('disabled');
				var details = e.find('detail').html();
				details = eval('('+details+')');
				self.details = details;
				if(details.length <= 1){
					$('#cashier-menu-detail').hide();
					detail = details[0];
					self.detailConfirm(detail);
					VALUE.write('.menu-info-price price_min','detail',detail.price)
					$('.menu-info-price price_max_container').hide();
					return;
				}
				self.detailConfirm({});
				$('#cashier-menu-detail').show();
				var detail_option = [];
				var detail_assist = [];
				var price_min = null;
				var price_max = null;
				for(var i in details){
					if(!price_min || price_min>details[i].price) price_min = details[i].price
					if(!price_max || price_max<details[i].price) price_max = details[i].price
					var d = details[i].options;
					if(!d){
						self.detailConfirm(details[i]);
						continue;
					}
					for(var j in d){
						var dd = d[j];
						var config_id = dd['config_id'];
						var config_name_cn = dd['config_name_cn']
						var config_length = detail_assist[config_id];
						var config_descripton = dd['config_descripton'];
						if(!config_length){
							detail_assist[config_id] = detail_option.length+1;
							config_length = detail_assist[config_id]
							detail_option.push({config_id:config_id,config_name_cn:config_name_cn,config_options:[],config_descripton:config_descripton})
						}
						config_length--;
						var option_name_cn = dd['option_name_cn'];
						// console.log(detail_option[config_length]['config_options'],option_name_cn,$.inArray(option_name_cn, detail_option[config_length]['config_options']));
						if($.inArray(option_name_cn, detail_option[config_length]['config_options'])==-1){
							detail_option[config_length]['config_options'].push(option_name_cn);
						}
					}
				}
				for(var i in detail_option){
					var options = [];
					var opt = detail_option[i]['config_options'];
					for(var j in opt){
						var option_name_cn = opt[j]
						options.push({option_name_cn:option_name_cn})
					}
					detail_option[i]['config_options'] = options;
				}
				VALUE.write('.menu-info-price price_min','detail',price_min)
				VALUE.write('.menu-info-price price_max','detail',price_max)
				RANK.clean($('#cashier-menu-detail-option-rank'));
				RANK.put($('#cashier-menu-detail-option-rank'),detail_option);
				// DETAIL.put($('#cashier-menu-detail'),$(t).find('.bc-list-detail-box'))
				$('#cashier-menu-detail').show();
			});
			//detail select
			$(document).on('click', '.cashier-menu-detail-option>div', function(event) {
				self.detailSelect(this);
			});
			$(document).on('click', '#mall-menu-info-add-to-cart', function(event) {
				var detail_id = $('#mall-menu-detail-id').html();
				if(!detail_id){
					// $('#cashier-detail-prices').fadeIn();
					return;
				}
				for(var i in self.details){
					if(self.details[i]['detail_id'] == detail_id){
						self.details[i]['name'] = $('#mall-menu-info name').html();
						self.details[i]['imgurl'] = $('#mall-menu-info imgurl img').attr('src');
						MALL.cart.add(self.details[i]);
						return;
					}
				}
			});
		},
		detailExist:function(s,ss){
			var selected = {};
			var details = this.details;
			for(var i in ss){
				selected[i] = ss[i];
			}
			for(var i in s){
				selected[i] = s[i];
			}
			// console.log(selected);
			for(var i0 in details){
				var options = details[i0].options
				if(!options) continue;
				// console.log(options);
				var exist = true;
				for(var config_id in selected){
					var config_exist = false;
					for(var i in options){
						if(options[i]['config_id'] == config_id && selected[config_id] == options[i]['option_name_cn']){
							config_exist = true;
							break;
						}
					}
					if(!config_exist){
						exist = false;
						break;
					}
				}
				if(exist){
					// console.log(details[i0]);
					return exist;//任意存在 返回真
				}
			}
			// console.log('notexist');
			return false;//不存在 返回假
		},
		detailConfirm:function(detail){
			var discount = detail.discount || 100;
			if(discount == 100){discount = null}
			$('.menu-info-selected detail_code').html(detail.detail_code)
			$('.menu-info-selected detail_id').html(detail.detail_id);
			VALUE.write('.menu-info-selected price','mall',detail.price)
			VALUE.write($('.menu-info-selected discount'),'mall',discount);
			VALUE.write($('.menu-info-selected deposit'),'mall',detail.deposit);
			VALUE.write($('.menu-info-selected options'),'mall',detail.options);
			if(detail.detail_id) $('#mall-menu-info .menu-info-add-to-cart').removeClass('disabled');
		},
		detailButton:function(e,es){
			var self = this;
			var ss = [];
			e.siblings().each(function(index, el) {
				var config_id = e.parents('.bc-rank-content').find('config_id').html();
				if(index){
					var s = [];
					var option = $(el).find('option_name_cn').html();
					s[config_id] = option;
					if(!self.detailExist(s,es)){
						$(el).addClass('disabled');
					}else{
						$(el).removeClass('disabled');
					}
				}
			});
			e.parents('.bc-rank-content').siblings('.bc-rank-content').each(function(index0, el0) {
				var config_id = $(el0).find('config_id').html();
				$(el0).find('.cashier-menu-detail-option>div').each(function(index, el) {
					if(index){
						var s = [];
						var option = $(el).find('option_name_cn').html();
						s[config_id] = option;
						if(!self.detailExist(s,es)){
							$(el).addClass('disabled');
						}else{
							$(el).removeClass('disabled');
						}
					}
				});

			});
		},
		detailPrice:function(selected){
			var selected_length = 0;
			for(var j in selected){
				selected_length++;
			}
			var self = this;
			var details = self.details;
			// console.log(details);
			var d = [];
			for(var i in details){
				//如果没有选择
				if(selected_length == 0){
					var detail_id 	= details[i].detail_id ;
					var price 		= details[i].price ;
					var detail_code = details[i].detail_code ;
					var discount 	= details[i].discount ;
					var options 	= details[i].options ;
					var deposit     = details[i].deposit ;
					//如果没有options 则视为唯一价格
					if(!details[i].options){
						d = [{options:options,discount:discount,detail_id:detail_id,price:price,detail_code:detail_code,deposit:deposit}];
						break;
					}else{
						d.push({options:options,discount:discount,detail_id:detail_id,price:price,detail_code:detail_code,deposit:deposit});
						continue;
					}
				}
				//没有option的跳过
				if(!details[i].options){
					continue;
				}
				var detail_selected = true;
				var config_exist = false;
				for(var j in details[i].options){
					var o = details[i].options[j];
					if(selected[o.config_id]){
						config_exist = true;
					}else{
						//该option没有在selected中
						// config_all_match = true;
					}
					if(selected[o.config_id] && o.option_name_cn != selected[o.config_id]){
						detail_selected = false;
						break;
					}
				}
				if(config_exist && detail_selected){
					var detail_id 	= details[i].detail_id ;
					var price 		= details[i].price ;
					var detail_code = details[i].detail_code ;
					var discount 	= details[i].discount ;
					var options 	= details[i].options ;
					var deposit     = details[i].deposit ;
					d.push({options:options,detail_id:detail_id,price:price,detail_code:detail_code,discount:discount,deposit:deposit});
					if(details[i].options.length == selected_length){
						d = [{options:options,discount:discount,detail_id:detail_id,price:price,detail_code:detail_code,deposit:deposit}];
						break;
					}
				}
			}
			var price_max = 0;
			var price_min = 0;
			var detail_code = '';
			// console.log(d);
			if(d.length == 1){
				self.detailConfirm(d[0]);
			}else if(d.length > 1){
				self.detailConfirm({});
				$('#mall-menu-info-add-to-cart').addClass('disabled')
			}
		},
		detailSelect:function(e){
			var e = $(e);
			if(e.hasClass('disabled')) return;
			if(e.hasClass('active')){
				e.removeClass('active');
			}else{
				e.addClass('active');e.siblings().removeClass('active');
			}
			var selected = {}
			$('#cashier-menu-detail-option-rank .bc-rank-content').each(function(index, el) {
				var config_id = $(el).find('config_id').html();
				var option = $(el).find('.cashier-menu-detail-option>div.active option_name_cn').html();
				if(config_id && option){
					selected[config_id] = option;
				}
			});

			this.detailButton(e,selected);
			this.detailPrice(selected);
		},
	},
	cart:{
		selected:[],
		init:function(){
			var self = this;
			$(document).on('bc-page-success bc-page-back', '.page', function() {
				var selected = self.selected;
				var a = 0;
				for(var i in selected){
					a += selected[i].amount;
				}
				$(".mall-cart-amount amount").html(a);
			});
			// $(document).on('bc-view-success bc-page-back', '.mall_cart,.mall_cart .bc-view', function() {
			// 	RANK.put("#mall-cart",self.selected);
			// 	var j = 0;
			// 	for(var i in self.selected){j++;}
			// 	if(j){
			// 		if(!ISMOBILE()){ self.order_get_price(); }
			// 		$('#mall-cart-empty').addClass('hidden');
			// 		$('.mall-cart-order-confirm').removeClass('hidden');
			// 	}else{
			// 		// self.getPrice();
			// 		$('#mall-cart-empty').removeClass('hidden');
			// 		$('.mall-cart-order-confirm').addClass('hidden');
			// 	}
			// });
			$(document).on('click', '.menu-cart-minus', function() {
				var detail_id = $(this).parents('.mall-cart-line').find('detail_id').html();
				var e = $(this).siblings('input[name="amount"]');
				var amount = (parseInt(e.val()) || 1) - 1 ;
				e.val(amount);
				console.log(detail_id,self.selected)
				for(var i in self.selected){
					if(self.selected[i].detail_id == detail_id){
						if(amount>0){
							self.selected[i].amount = amount;
						}else{
							self.selected.splice(i,1);
							var ee = $(this).parents('.mall-cart-line')
							ee.fadeOut(100,function(){
								ee.remove();
							})
						}
					}
				}
				if(!ISMOBILE()){ self.order_get_price(); }
			});
			$(document).on('click', '.menu-cart-plus', function() {
				var detail_id = $(this).parents('.mall-cart-line').find('detail_id').html();
				var e = $(this).siblings('input[name="amount"]');
				var amount = (parseInt(e.val()) || 1) + 1 ;
				e.val(amount);
				for(var i in self.selected){
					if(self.selected[i].detail_id == detail_id){
						if(amount>0){
							self.selected[i].amount = amount;
						}else{
							self.selected.splice(i,1);
							var ee = $(this).parents('.mall-cart-line')
							ee.fadeOut(100,function(){
								ee.remove();
							})
						}
						break;
					}
				}
				if(!ISMOBILE()){ self.order_get_price(); }
			});
			$(document).on('change', '.menu-cart-amount input', function() {
				var detail_id = $(this).parents('.mall-cart-line').find('detail_id').html();
				var e = $(this)
				var amount = parseInt(e.val());
				if(!(amount>=0)){
					amount = 1;
					e.val(amount);
				}
				for(var i in self.selected){
					if(self.selected[i].detail_id == detail_id){
						if(amount>0){
							self.selected[i].amount = amount;
						}else{
							self.selected.splice(i,1);
							var ee = $(this).parents('.mall-cart-line')
							ee.fadeOut(100,function(){
								ee.remove();
							})
						}
						break;
					}
				}
				if(!ISMOBILE()){ self.order_get_price(); }
			});
			// $(document).on('click', '.menu-cart-remove', function() {
			// 	if(!confirm("确认删除产品？")) return
			// 	var detail_id = $(this).parents('.mall-cart-line').find('detail_id').html();
			// 	$.ajax({
			// 		url:URL.cart_remove,
			// 		type:'GET',
			// 		data:{
			// 			detail_id:detail_id
			// 		},
			// 		success:function (e) {
			// 			if(!e.state){
			// 				alert()
			// 			}
             //        }
			// 	})
				// for(var i in self.selected){
				// 	if(self.selected[i].detail_id == detail_id){
				// 		self.selected.splice(i,1);
				// 		var ee = $(this).parents('.mall-cart-line')
				// 		ee.fadeOut(100,function(){
				// 			ee.remove();
				// 		})
				// 		break;
				// 	}
				// }
			// 	if(!ISMOBILE()){ self.order_get_price(); }
			// });
			$(document).on('click', '#mall-cart-clean', function() {
				if(!confirm("确认清空购物车产品？")) return
				var e = $('.bc-rank-content.mall-cart-line-rank');
				self.selected = [];
				e.fadeOut(100,function(){
					e.remove();
					$('#mall-cart-empty').removeClass('hidden');
					$('.mall-cart-order-confirm').addClass('hidden');
				})
			});
			$(document).on('click', '#cart-confirm-mobile', function(event) {
				if ( !$('#mall-cart-address').val() ){
					ERROR.top('确认','请填收货地址');
					return;
				}
				location.href='#mall_cart_pay';
			});
			$(document).on('bc-view-success', '.page.mall_cart_pay .bc-view', function() {
				// TOAST.load('计算价格');
				// self.order_get_price()
			});
			$(document).on('bc-info-success', '.mall-cart-result.bc-info', function(e,res) {
				TOAST.stop();
			});
			$(document).on('bc-info-error', '.mall-cart-result.bc-info', function(e,res) {
				TOAST.stop();
				ERROR.top("价格计算",res);
			});

			// POST.init(document,{
			// 	// url:'/mall/order_create',
			// 	// text:'准备订单',
			// 	input:function(){
			// 		var rt = self.input();
			// 		rt['member_discount_none'] = 1;
			// 		return rt;
			// 	},
			// 	success:function(e,res){
			// 		var order_id = res.data.info.order_id;
			// 		if(!order_id){
			// 			alert('订单号错误');
			// 			return;
			// 		}
			// 		var amount = 0;
			// 		for(var i in self.selected){
			// 			amount += self.selected[i].amount
			// 		}
			// 		PAY.order_id = order_id;
			// 		PAY.body = self.selected[0].name+"等 "+amount+"件商品 [重卡汇]";
			// 		$(document).trigger('bc-pay-tenpay');
			// 	},
			// 	msg:{
			// 		// "area error":"请填写区域",
			// 		// "desk error":"请填写桌号",
			// 	}
			// },'#mall-cart-pay-wechat');
			$(document).on('bc-pay-success', function(event) {
				location.href='#order';
				LIST.reload('#order-list');
				MODAL.close('.modal')
			});

			$(document).on('change', '#mall-cart-options input[name="people"]', function(event) {
				if(!ISMOBILE()){ self.order_get_price(); }
			});
			// $(document).on('bc-pay-tenpay-qrcode-ready',function(e,res){
			// console.log(res);
			// })
		},
		input:function(){
			var self = this;
			var rt = {}
			$('#mall-cart-options').find('input').each(function(index, el) {
				var name = $(el).attr('name');
				var value = $(el).val() || $(el).attr('placeholder');
				rt[name] = value;
			});
			$('#mall-cart-options').find('textarea').each(function(index, el) {
				var name = $(el).attr('name');
				var value = $(el).val();
				rt[name] = value;
			});
			var detail = {};
			for( var i in self.selected ){
				detail[self.selected[i].detail_id] = self.selected[i].amount
			}
			detail = JSON.stringify(detail);
			rt.detail = detail;
			return rt;
		},
		order_get_price:function(){
			var self = this;
			INFO.reload(PAGE.current.find('.mall-cart-result.bc-info'),self.input());
		},
		add:function(detail){
			if(!INFO.cache.user || !INFO.cache.user.tel){
				if(INFO.cache.user){
					alert('请绑定手机号码')
					location.href='#bind_tel';
				}else{

					if(WEIXIN.is() && confirm('通过微信自动登陆？')){
						WEIXIN.login();
						return;
					}else{
						location.href='#login';
					}
				}
				return;
			}
			var self = this;
			var detail_id = detail.detail_id;
			var selected = self.selected;
			var exist = false;
			$.ajax({
				url:URL.cart_add,
				data:{
					detail_id:detail_id
				},
				success:function(res){
                    $.ajax({
                        url:'/cart/amount',
                        success:function (e) {
                            if(e.data.amount==0){
                                $('#cartamount').css('color','white')
                                $('#mall-info-cart').css('color','white')
                            }else {
                                $('#cartamount').html(e.data.amount)
                                $('#mall-info-cart').html(e.data.amount)
                                $('#cartamount').css('color', '#FFA500')
                                $('#mall-info-cart').css('color', 'white')
                            }
                        }
                    })
				}
			})
			for(var i in selected){
				if(selected[i].detail_id==detail_id){exist = true;break;}
			}
			if(exist){
				selected[i]['amount'] ++;
			}else{
				detail.amount = 1;
				selected.push(detail);
			}

			var a = 0;
			for(var i in selected){
				a += selected[i].amount;
			}
			// TOAST.success('添加')
			$(".mall-cart-amount amount").html(a);
			$(".mall-cart-amount").fadeIn();
		}
	}
}
USER = {
    urls:{
        order_list 		: '/order/getlist' ,
        order_remove 	: '/order/remove' ,
        info 			: '/user/info' ,
    },
    init:function(){
        this.order.init();
    },
    order:{
        init:function(){

            $(document).on('bc-pay-success', function(event) {
                LIST.reload('#order-list');
                MODAL.close('.modal')
            });
            //order-remove
            POST.init(document,{
                method:'click touchstart',
                url:USER.urls.order_remove,
                stop:function(e){
                    var order_id = $(e).parents('.bc-list-line').find('order_id').html();
                    if(!order_id) return true;
                },
                text:"删除订单",
                confirm:true,
                input:function(e){
                    var order_id = $(e).parents('.bc-list-line').find('order_id').html();
                    return {order_id:order_id}
                },
                success:function(e){
                    var l = $(e).parents('.bc-list-line');
                    l.fadeOut(300,function(){
                        l.remove();
                    })
                }
            },'.user-order-remove')
            //order-remove-all
            POST.init(document,{
                url:USER.urls.order_remove,
                stop:function(e){
                    var ids = LIST.selected(e);
                    if(!ids.length) return true;
                },
                text:"删除",
                confirm:function(e){
                    var ids = LIST.selected(e);
                    var target = ids.length+"个订单";
                    return {target:target}
                },
                input:function(e){
                    var ids = LIST.selected(e);
                    ids = ids.join(",")
                    return {order_id:ids};
                },
                success:function(e){
                    LIST.reload('#user-order-list')
                }
            },'#user-order-remove-all')
            $(document).on('click touchstart', '.user-order-pay', function() {
                var l = $(this).parents('.bc-list-line');
                var order_id = l.find('order_id').html();
                var mallName = '';
                l.find('detail name').each(function(index, el) {
                    if(index){
                        mallName ? mallName += ',' + $(el).html() : mallName = $(el).html()
					}
                });
                var amount = 0;
                // console.log(name);
                console.log(1231231231312312);
                l.find('detail').children().each(function(index, el) {
                    if(index) amount += parseInt($(el).find('amount').html()) || 0;
                });
                // var cc = l.find('class').eq(1).html();
                // var ccc = {'mall':'重卡汇商城'};
                // cc = ccc[cc];
                PAY.order_id = order_id;
                PAY.body = localStorage.mall_name+"等 "+localStorage.amount+"件商品 [重卡汇]";
                // PAY.body = mallName+"等 "+amount+"件商品 ["+cc+"]";
                $(document).trigger('bc-pay-tenpay');
            });
        }
    },
    //notRedirect 不进行跳转
    login:function(notRedirect){
        if(!INFO.cache.user){
            if(WEIXIN.is()){
                WEIXIN.login();
                return true;
            }
            if(!notRedirect){
                alert('请登录');
                location.href='#login';
                return true;
            }
        }
        if(!notRedirect && !INFO.cache.user.tel){
            alert('请绑定手机号码');
            location.href='#bind_tel';
            return true;
        }
    }
}
$(function(){
    $(document).on('bc-pay-success' , function(event,order_id) {
        LIST.reload('#user-order-list')
    });
    USER.init();
    MALL.init();
})